#version 150

#moj_import <fog.glsl>

uniform sampler2D Sampler0;

uniform vec4 ColorModulator;
uniform float FogStart;
uniform float FogEnd;
uniform vec4 FogColor;

in float vertexDistance;
in vec4 ssao;
in vec2 texCoord0;
in vec3 normal;
in vec4 ViewPosition;

out vec4 fragColor;

bool check_float(float textureAlpha, float targetAlpha) {
	
	float targetLess = targetAlpha - 0.001;
	float targetMore = targetAlpha + 0.001;
	return (textureAlpha > targetLess && textureAlpha < targetMore);
	
}

void main() {
    vec4 diffuse = texture(Sampler0,texCoord0);
    if(diffuse.a < 0.1)discard;
    //light scene
    vec4 lightColor = vec4(0.5, 0.5, 0.5, 1.0);
    vec4 lightPosition = vec4(0.0, 1.0, 0.0, 1.0);
    //vectors
    vec3 lightDirection = normalize(lightPosition.xyz - ViewPosition.xyz);
    vec3 viewDirection = normalize(ViewPosition.xyz);
    vec3 midDirection = normalize(lightDirection - viewDirection);
    //other arguments
    float viewDistance = vertexDistance * vertexDistance;
    float gloss = 256.0;
    //ambient diffuse and specular
    vec4 ambiColor = diffuse       * ssao;
    vec4 diffColor = diffuse       * (lightColor / viewDistance) *     max(0.0 ,dot(lightDirection, normal));
    vec4 specColor = diffuse * 2.0 * (lightColor / viewDistance) * pow(max(0.0 ,dot(midDirection,   normal)),gloss);

    //normal mappig
    if(check_float(diffuse.a,254.0/255.0)){
        mat4 normalMat = mat4(
            cross(normalize(ViewPosition.xyz), normal),                0.0,
            cross(cross(normalize(ViewPosition.xyz), normal), normal), 0.0,
            normal,                                                    0.0,
            0.0,                0.0,               0.0,                1.0
        );
        float strength = 3;
        vec3 aNormal = vec3(
            pow((normalMat * texture(Sampler0, texCoord0)).x,strength),
            pow((normalMat * texture(Sampler0, texCoord0)).y,strength),
            pow((normalMat * texture(Sampler0, texCoord0)).z,strength)
        );
        ambiColor = vec4(0.7,0.7,0.7,1.0)       * ssao;
        diffColor = vec4(0.7,0.7,0.7,1.0)       * (lightColor / viewDistance) *     max(0.0 ,dot(lightDirection, aNormal));
        specColor = vec4(0.7,0.7,0.7,1.0) * 2.0 * (lightColor / viewDistance) * pow(max(0.0 ,dot(midDirection,   normal)),gloss);
    }

    //combined color
    vec4 color = (ambiColor + diffColor + specColor) * ColorModulator;
    fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor);
}
